/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-05-08
 * Time: 19:25
 */
//就不写带泛型的 自己实现阻塞队列 直接写朴素代码 存储的元素是int
//基于数组来实现 循环队列
class MyBlockingQueue {
    private int[] items = new int[1000];
    //约定[head,tail) 队列的有效元素
    volatile private int head = 0;
    volatile private int tail = 0;
    volatile private int size = 0;

    //入队列
    synchronized public void put(int elem) throws InterruptedException {
        //不只判断一次 多确认
        while(size == items.length) {
            //队列满的插入失败
            //return;
            //加阻塞
            this.wait();
        }
        //把新元素放到tail所在的位置上
        items[tail] = elem;
        tail++;
        //万一达到末尾,就需让tail从头来
        if(tail == items.length) {
            tail = 0;
        }
        //tail = tail % items.length; 不推荐
        size++;
        this.notify();
    }

    //出队列
    synchronized public Integer take() throws InterruptedException {
        while(size == 0) {
            //size为0则没有元素可以出
            this.wait();
        }
        int value = items[head];
        head++;
        if(head == items.length) {
            head = 0;
        }
        size--;
        //有元素出队列 队列不为满 则要唤醒
        this.notify();
        return value;
    }
}

public class ThreadDemo18 {

    public static void main(String[] args) {
    MyBlockingQueue queue = new MyBlockingQueue();
    // 消费者
        Thread t1 = new Thread(()-> {
            while(true) {
                try {
                    int value = queue.take();
                    Thread.sleep(1000);
                    System.out.println("消费：" + value);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 生产者
        Thread t2 = new Thread(()-> {
            int value = 0;
            while(true) {
                try {
                    System.out.println("生产：" + value);
                    queue.put(value);

                    value++;
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();

    }
}
